package com.nowcoder.community.interceptor;

import com.nowcoder.community.pojo.LoginTicket;
import com.nowcoder.community.pojo.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CookieUtil;
import com.nowcoder.community.util.HostHolder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor{

    @Autowired
    @Qualifier("userService")
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

//    @Autowired
//    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中获取凭证
        String ticket = CookieUtil.getValue(request, "ticket");

        if (ticket != null){
            //查询凭证
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
//            System.out.println("登录凭证：" + loginTicket);

//            System.out.println("判断" + loginTicket.getExpired().after(new Date()));
            //检查凭证是否有效（loginTicket示例是否存在；凭证状态是否有效；过期时间是否在当前时间之后）
            if (loginTicket!=null && loginTicket.getStatus()==0 && loginTicket.getExpired().after(new Date())){


                User user = userService.findUserById(loginTicket.getUserId());

//                System.out.println("登录后的用户：" + user);

                //在本次请求中持有用户（每个请求线程中设置的user不同）
                hostHolder.setUser(user);
                //构建用户认证后的结果，存入SecurityContext中，以便于接下来的授权操作
                Authentication authentication = new UsernamePasswordAuthenticationToken(user,
                        user.getPassword(), userService.getAuthorities(user.getId()));
                SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
            }

        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
//        System.out.println("用户：" + user);
        if (user!=null && modelAndView!=null){
            modelAndView.addObject("loginUser", user);
        }
    }

    //使用完user实例之后在ThreadLocal中将其清理
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SecurityContextHolder.clearContext();
        //ElasticSearch中的请求未关闭。I/O资源未关闭时，容易触发FullGC。
//        restHighLevelClient.close();

        hostHolder.clear();
    }
}
